package com.sl.au.controller;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.sl.au.entity.Account;
import com.sl.au.entity.Contract;
import com.sl.au.entity.ContractCruxDate;
import com.sl.au.entity.ContractInfo;
import com.sl.au.entity.ContractPart;
import com.sl.au.entity.ContractPump;
import com.sl.au.entity.ContractRepair;
import com.sl.au.entity.Customer;
import com.sl.au.entity.DivideScale;
import com.sl.au.entity.EXDELoginInfo;
import com.sl.au.entity.ExdeTbOPPlanTask;
import com.sl.au.entity.Module;
import com.sl.au.entity.News;
import com.sl.au.entity.Option;
import com.sl.au.entity.QuoteDevice;
import com.sl.au.entity.QuoteReplacement;
import com.sl.au.entity.Root;
import com.sl.au.entity.User;
import com.sl.au.service.ActivitiService;
import com.sl.au.service.AttachmentService;
import com.sl.au.service.AuditNodeService;
import com.sl.au.service.ContractService;
import com.sl.au.service.CustomerService;
import com.sl.au.service.ExcelService;
import com.sl.au.service.ExdeSchedulingService;
import com.sl.au.service.OperateLogService;
import com.sl.au.service.OptionService;
import com.sl.au.service.SaleAreaService;
import com.sl.au.service.ExcelService;
/**
 * 合同管理控制器
 * 
 * @author XH
 *
 *
 */
@RestController
@RequestMapping(value = "/ui/contract/")
public class ContractController extends BaseController {

	@Autowired
	ContractService contractService;

	@Autowired
	CustomerService customerService;

	@Autowired
	OptionService optionService;

	@Autowired
	ExcelService excelService;
	
	@Autowired
	AttachmentService attachmentService;
	
	@Autowired
	OperateLogService operateLogService;

	@Autowired
	ActivitiService activitiService;
	@Autowired
	AuditNodeService auditNodeService;
	
	@Autowired
	ExdeSchedulingService exdeSchedulingService;
	//
	@Autowired
	SaleAreaService saleAreaService;
	/**
	 * 返回查看合同界面中实际发货时间、调试完成时间、验收完成时间
	 * @param taskId
	 * @param contractId
	 * @param contractType
	 * @return
	 */
	@RequestMapping(value = "audit-view/{contractId}/json", method = RequestMethod.GET)
	public Map<String,Object> aduitDateContractJSON( @PathVariable String contractId) {
		Map<String,Object> map=new HashMap<>();
		ContractInfo contractPart = null;
		contractPart = contractService.getDateContractById(contractId);
		map.put("contract", contractPart);
		return map;
	}

	/**
	 * 合同管理页面显示
	 */
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView index() {
		Module module = this.getPageModule("contractInfo");
		ModelAndView modelAndView = this.createLayoutView("contract/contractindex");
		modelAndView.addObject("industryInfos", optionService.getRepository().findByGroup("行业"));
		modelAndView.addObject("orderAreas",contractService.getSuperiorAreasBySuperior(this.getMyAccount().getUser().getSaleArea().getSuperior()));
		modelAndView.addObject("module", module);
		
		return modelAndView;
	}

	/**
	 * 获取页面数据
	 */
	@RequestMapping(value = "getpage", method = RequestMethod.GET)
	public Map<String, Object> getPage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String superior = a.getUser().getSaleArea().getSuperior();
		String areaName = a.getUser().getSaleArea().getAreaName();
		String name = "contractInfo";
		Module module = this.getPageModule(name);
		String dataFilter = module.getDataFilter();
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		if (userId == null) {
			userId = "";
		}
		if (superior == null) {
			superior = "";
		}
		if (areaName == null) {
			areaName = "";
		}
		if (dataFilter == null) {
			dataFilter = "";
		}
		condition.put("key", key);
		condition.put("userId", userId);
		condition.put("superior", superior);
		condition.put("areaName", areaName);
		condition.put("dataFilter", dataFilter);
		List<ContractInfo> contracts = contractService.getContractInfos(start, length, condition, null, null);
		long count = contractService.getContractInfosCount(condition);
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	/**
	 * HQL获取页面数据
	 */
	@RequestMapping(value = "getpage1", method = RequestMethod.GET)
	public Map<String, Object> getPage1(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> qMap = new HashMap<String, Object>();
		Map<String, Object> condition = new HashMap<String, Object>();
		Map<String, Object>numMap=new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		Account a = this.getMyAccount();
		Module module = this.getPageModule("contractInfo");
		String dataFilter = module.getDataFilter();
		User user = a.getUser();
		this.getQueryParams(qMap,numMap);
		condition.put("dataFilter", dataFilter);
		condition.put("qMap", qMap);
		condition.put("numMap", numMap);
		List<ContractInfo> contracts = contractService.getQueryContractsHql(start, length, condition, user, "createTime",
				"desc");
		long count=contractService.getQueryContractsHql(0, Integer.MAX_VALUE, condition, user, "createTime","desc").size();
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	private void getQueryParams(Map<String, Object> qMap,Map<String, Object>numMap){
//		String names[]={"supplierCode","contractType",
//				"auditState","belongArea","totalSum","stop",
//				"freightCharge","projectName","orderUnit","orderAddress",
//				"orderDelegate","orderPhone","orderZip","orderArea",
//				"postUnit","postAddress","postDelegate","postPhone","postZip"};
		String names[]={"supplierCode","contractType",
				"belongArea","stop",
				"projectName","orderUnit","orderAddress",
				"orderDelegate","orderPhone","orderArea",
				"postUnit","postAddress","postDelegate","postPhone","state","cstate"};
		String nums[]={"freightCharge","orderZip","postZip"};
		String ints[]={"totalSum"};
		String dates[]={"createTime","signedDate","scheduleDate","giveOutDate","deliveryDate","debugDate","acceptanceDate"};
		for(String name:names){
			if(StringUtils.hasText(request.getParameter(name))){
				qMap.put(name, request.getParameter(name));
			}
		}
		for(String date:dates){
			if(null!=this.getDateQueryItem(date)){
				qMap.put(date,this.getDateQueryItem(date));
			}
		}
		if(null!=this.getDoubleQueryItem("totalSum")){
			qMap.put("totalSum",this.getDoubleQueryItem("totalSum"));
		}
		for(String n:nums){
			if(StringUtils.hasText(request.getParameter(n))){
				numMap.put(n, request.getParameter(n));
			}
		}
	}
	
	/**
	 * 暂停、撤销、终止合同
	 */
	@RequestMapping(value = "suspendAndRevocationContract/{contractInfo}/{contractType}/{type}", method = RequestMethod.GET)
	public Map<String, Object> suspendAndRevocationContract(HttpServletRequest request,@PathVariable String contractInfo, @PathVariable String contractType,@PathVariable String type) {
		Map<String, Object> map = new HashMap<String, Object>();
		int result = 0;
		Account a = this.getMyAccount();
		User user = a.getUser();
		if (StringUtils.hasText(contractInfo)) {
			String code = "";
			if (contractType.equals("项目合同")){
				Contract old = contractService.getRepository().findOne(contractInfo);
				if (old!=null){
					code = old.getSupplierCode();
				}
			}else if (contractType.equals("备件合同")){
				ContractPart old = contractService.getRepository2().findOne(contractInfo);
				if (old!=null){
					code = old.getSupplierCode();
				}
			}else if (contractType.equals("备泵合同")){
				ContractPump old = contractService.getRepository3().findOne(contractInfo);
				if (old!=null){
					code = old.getSupplierCode();
				}
			}else if (contractType.equals("维修合同")){
				ContractRepair old = contractService.getRepository4().findOne(contractInfo);
				if (old!=null){
					code = old.getSupplierCode();
				}
			}
			result = contractService.suspendAndRevocationContractInfo(contractInfo,contractType,type);
			String content  = type + "【" + contractType + "】【" + code + "】";
			operateLogService.log(user, type + "合同", content);
		}
		map.put("code", result);
		return map;
	}
	
	/**
	 * 打印备件合同邮寄信息
	 */
	@RequestMapping(value = "printbj/{customerId}", method = RequestMethod.GET)
	public ResponseEntity<Resource> printbj(@PathVariable String customerId) throws IOException {
		Account account = this.getMyAccount();
		User user = account.getUser();
		//String sender = account.getLoginInfo().getName();
		String filename = contractService.genQuoteDocx(customerId, user);
		Resource file = null;
		String shortName = "邮寄地址.docx";
		if (null != filename) {
			file = attachmentService.loadAsResource(filename);
			String url = file.getURL().toString();
			int a = url.lastIndexOf('/');
			shortName = url.substring(a + 1);
		}
		return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
						"attachment; charset=UTF-8;filename=\"" + java.net.URLEncoder.encode(shortName, "UTF-8") + "\"")
				.body(file);
	}
	
	/**
	 * 获得与客户相关的合同
	 */
	@RequestMapping(value = "getCustomerContract", method = RequestMethod.GET)
	public Map<String, Object> getCustomerContract(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, String> condition = new HashMap<String, String>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		String customerId = request.getParameter("customerId");
		if (key == null) {
			key = "";
		}
		key = key.replaceAll("\\s+", "");
		condition.put("key", key);
		condition.put("customerId", customerId);
		List<ContractInfo> custmerContracts = contractService.getContractInfosByCustomer(start, length, condition, null,
				null);
		long count = contractService.getContractInfosByCustomerCount(condition);
		map.put("data", custmerContracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 获取项目合同
	 */
	@RequestMapping(value = "getContract", method = RequestMethod.GET)
	public Map<String, Object> getContract(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String key = request.getParameter("key");
		if (key == null) {
			key = "";
		}
		List<Contract> contracts = contractService.getContracts(start, length, key, null, null);
		Long count = (long) contractService.getContractsCount(key);
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 获取当前合同关键点
	 */
	@RequestMapping(value = "getCruxDatepage", method = RequestMethod.GET)
	public Map<String, Object> getCruxDatepage(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String contractId = request.getParameter("contractId");
		if (contractId == null) {
			contractId = "";
		}
		List<ContractCruxDate> contractCruxDates = contractService.
				getContractCruxDates(start, length, contractId, null, null);
		Long count = (long) contractService.getContractCruxDatesCount(contractId);
		map.put("data", contractCruxDates);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}
	
	/**
	 * 新建/编辑合同关键点保存
	 */
	@RequestMapping(value = "saveContractCruxDate", method = RequestMethod.POST)
	public Map<String, Object> saveContractCruxDate(@RequestBody ContractCruxDate contractCruxDate, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (contractCruxDate != null) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			boolean isEdit = false;
			ContractCruxDate old = contractService.getRepository10().findOne(contractCruxDate.getId());
			if (old!=null){
				isEdit = true;
				contractCruxDate.setUser(old.getUser());
			} else{
				contractCruxDate.setUser(user);
			}
			contractService.saveContractCruxDate(contractCruxDate);
			String cId = contractCruxDate.getContractID();
			String cType = contractCruxDate.getContractType();
			String cCode = contractService.getSupplierCodeByTypeAndId(cType, cId);
			if(isEdit){
				String content  = "编辑【" + cType + "】【" + cCode + "】"
						+ "关键点【" + contractCruxDate.getExecutiveType() + "】";
				operateLogService.log(user, "编辑合同关键点", content);
			}else{
				String content  = "新增【" + cType + "】【" + cCode + "】"
						+ "关键点【" + contractCruxDate.getExecutiveType() + "】";
				operateLogService.log(user, "新增合同关键点", content);
			}
		}
		map.put("code", 0);
		return map;
	}
	
	/**
	 * 删除合同关键点
	 */
	@RequestMapping(value = "deleteContractCruxDate", method = RequestMethod.GET)
	public Map<String, Object> deleteContractCruxDate(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		if (StringUtils.hasText(ids)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			String[] cruxDateIds = ids.split(",");
			for (String id : cruxDateIds){
				ContractCruxDate oldD = contractService.getRepository10().findOne(id);
				if (oldD!=null){
					String cId = oldD.getContractID();
					String cType = oldD.getContractType();
					String cCode = contractService.getSupplierCodeByTypeAndId(cType, cId);
					String content  = "删除【" + cType + "】【" + cCode + "】关键点【" + oldD.getExecutiveType() + "】";
					operateLogService.log(user, "删除合同关键点", content);
				}
			}
			contractService.deleteContractCruxDate(ids);
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 删除合同及其关联的数据
	 */
	@RequestMapping(method = RequestMethod.DELETE)
	public Map<String, Object> deleteContract(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String contractInfo = request.getParameter("contractInfo");
		if (StringUtils.hasText(contractInfo)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			// params[0]是contractId数据; params[1]是contractType数据
			String[] params = contractInfo.split(":");
			if (params.length == 2){
				String[] ids = params[0].split(",");
				String[] types = params[1].split(",");
				int i = 0;
				for (String id : ids){
					String code = "";
					if (types[i].equals("项目合同")){
						Contract old = contractService.getRepository().findOne(ids[i]);
						if (old!=null){
							code = old.getSupplierCode();
						}
					}else if (types[i].equals("备件合同")){
						ContractPart old = contractService.getRepository2().findOne(ids[i]);
						if (old!=null){
							code = old.getSupplierCode();
						}
					}else if (types[i].equals("备泵合同")){
						ContractPump old = contractService.getRepository3().findOne(ids[i]);
						if (old!=null){
							code = old.getSupplierCode();
						}
					}else if (types[i].equals("维修合同")){
						ContractRepair old = contractService.getRepository4().findOne(ids[i]);
						if (old!=null){
							code = old.getSupplierCode();
						}
					}
					String content  = "删除【" + types[i++] + "】【" + code + "】";
					operateLogService.log(user, "删除合同", content);
				}
			}
			contractService.deleteContract(contractInfo);
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 新建合同
	 */
	@RequestMapping(value = "contractAdd/{contractType}")
	public ModelAndView newContract(@PathVariable String contractType) {
		ModelAndView modelAndView = this.createLayoutView("contract/contract-add");
		if (contractType.equals("备件合同")) {
			modelAndView = this.createLayoutView("contract/part-contract-add");
		} else if (contractType.equals("备泵合同")) {
			modelAndView = this.createLayoutView("contract/pump-contract-add");
		} else if (contractType.equals("维修合同")) {
			modelAndView = this.createLayoutView("contract/repair-contract-add");
		}
		modelAndView = getSelect(contractType, modelAndView);
		
		return modelAndView;
	}

	/**
	 * 编辑合同,基本信息页面显示
	 * 
	 * @param contractId,合同Id
	 * @param contractType,合同类型
	 * @return
	 */
	@RequestMapping(value = "contractEdit/{contractId}/{contractType}")
	public ModelAndView contractEdit(@PathVariable String contractId, @PathVariable String contractType) {
		String contractCode = "";
		ModelAndView modelAndView = this.createLayoutView("contract/contract-edit");
		if (contractType.equals("备件合同")) {
			modelAndView = this.createLayoutView("contract/part-contract-edit");
			ContractPart contractPart = null;
			if (contractId != null && !contractId.equals("")) {
				contractPart = contractService.getContractPartById(contractId);
				if (contractPart.getSupplierCode()!=null){
					contractCode = contractPart.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPart);
		} else if (contractType.equals("备泵合同")) {
			modelAndView = this.createLayoutView("contract/pump-contract-edit");
			ContractPump contractPump = null;
			if (contractId != null && !contractId.equals("")) {
				contractPump = contractService.getContractPumpById(contractId);
				if (contractPump.getSupplierCode()!=null){
					contractCode = contractPump.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPump);
		} else if (contractType.equals("维修合同")) {
			modelAndView = this.createLayoutView("contract/repair-contract-edit");
			ContractRepair contractRepair = null;
			if (contractId != null && !contractId.equals("")) {
				contractRepair = contractService.getContractRepairById(contractId);
				if (contractRepair.getSupplierCode()!=null){
					contractCode = contractRepair.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractRepair);
		} else {
			Contract contract = null;
			if (contractId != null && !contractId.equals("")) {
				contract = contractService.getContractById(contractId);
				if (contract.getSupplierCode()!=null){
					contractCode = contract.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contract);
		}
		modelAndView = getSelect(contractType, modelAndView);
		modelAndView.addObject("contractCode", contractCode);
		modelAndView.addObject("contractId", contractId);
		return modelAndView;
	}

	/**
	 * 提交合同页面
	 */
	@RequestMapping(value = "audit/{contractId}/{contractType}", method = RequestMethod.GET)
	public ModelAndView submitContract(@PathVariable String contractId, @PathVariable String contractType) {
		String contractCode = "";
		ModelAndView modelAndView = this.createLayoutView("contract/contract-submit");
		if (contractType.equals("备件合同")) {
			modelAndView = this.createLayoutView("contract/part-contract-submit");
			ContractPart contractPart = null;
			if (contractId != null && !contractId.equals("")) {
				contractPart = contractService.getContractPartById(contractId);
				if (contractPart.getSupplierCode()!=null){
					contractCode = contractPart.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPart);
		} else if (contractType.equals("备泵合同")) {
			modelAndView = this.createLayoutView("contract/pump-contract-submit");
			ContractPump contractPump = null;
			if (contractId != null && !contractId.equals("")) {
				contractPump = contractService.getContractPumpById(contractId);
				if (contractPump.getSupplierCode()!=null){
					contractCode = contractPump.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPump);
		} else if (contractType.equals("维修合同")) {
			modelAndView = this.createLayoutView("contract/repair-contract-submit");
			ContractRepair contractRepair = null;
			if (contractId != null && !contractId.equals("")) {
				contractRepair = contractService.getContractRepairById(contractId);
				if (contractRepair.getSupplierCode()!=null){
					contractCode = contractRepair.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractRepair);
		} else {
			Contract contract = null;
			if (contractId != null && !contractId.equals("")) {
				contract = contractService.getContractById(contractId);
				if (contract.getSupplierCode()!=null){
					contractCode = contract.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contract);

		}
		modelAndView = getSelect(contractType, modelAndView);
		modelAndView.addObject("contractCode", contractCode);
		modelAndView.addObject("contractId", contractId);

		return modelAndView;
	}

	/**
	 * 审批合同审批者页面
	 */
	@RequestMapping(value = "audit-view/{taskId}/{contractId}/{contractType}", method = RequestMethod.GET)
	public ModelAndView auditViewContract(@PathVariable String taskId, @PathVariable String contractId,
			@PathVariable String contractType) {
		String contractCode = "";
		String pInstId=null;
		ModelAndView modelAndView = this.createLayoutView("contract/contract-audit-view");
		if (contractType.equals("备件合同")) {
			modelAndView = this.createLayoutView("contract/part-contract-view");
			ContractPart contractPart = null;
			if (contractId != null && !contractId.equals("")) {
				contractPart = contractService.getContractPartById(contractId);
				pInstId=contractPart.getProcessInstId();
				if (contractPart.getSupplierCode()!=null){
					contractCode = contractPart.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPart);
		} else if (contractType.equals("备泵合同")) {
			modelAndView = this.createLayoutView("contract/pump-contract-view");
			ContractPump contractPump = null;
			if (contractId != null && !contractId.equals("")) {
				contractPump = contractService.getContractPumpById(contractId);
				pInstId=contractPump.getProcessInstId();
				if (contractPump.getSupplierCode()!=null){
					contractCode = contractPump.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractPump);
		} else if (contractType.equals("维修合同")) {
			modelAndView = this.createLayoutView("contract/repair-contract-view");
			ContractRepair contractRepair = null;
			if (contractId != null && !contractId.equals("")) {
				contractRepair = contractService.getContractRepairById(contractId);
				pInstId=contractRepair.getProcessInstId();
				if (contractRepair.getSupplierCode()!=null){
					contractCode = contractRepair.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contractRepair);
		} else {
			Contract contract = null;
			if (contractId != null && !contractId.equals("")) {
				contract = contractService.getContractById(contractId);
				pInstId=contract.getProcessInstId();
				if (contract.getSupplierCode()!=null){
					contractCode = contract.getSupplierCode();
				}
			}
			modelAndView.addObject("contract", contract);

		}
		boolean isAudit = true;
		if (taskId.equals("0")){
			isAudit = false;
		}
		modelAndView = getSelect(contractType, modelAndView);
		modelAndView.addObject("contractCode", contractCode);
		modelAndView.addObject("contractId", contractId);
		modelAndView.addObject("taskId", taskId);
		modelAndView.addObject("isAudit", isAudit);
		modelAndView.addObject("auditnodes", auditNodeService.getRepository().getNodesById(pInstId,contractId));

		return modelAndView;
	}
	/**
	 * 审批合同审批者页面JSON
	 */
	@RequestMapping(value = "audit-view/{taskId}/{contractId}/{contractType}/json", method = RequestMethod.GET)
	public Map<String,Object> auditViewContractJSON(@PathVariable String taskId, @PathVariable String contractId,
			@PathVariable String contractType) {
		String contractCode = "";
		String pInstId=null;
	Map<String,Object> map=new HashMap<>();
		
		if (contractType.equals("备件合同")) {
			
			ContractPart contractPart = null;
			if (contractId != null && !contractId.equals("")) {
				contractPart = contractService.getContractPartById(contractId);
				pInstId=contractPart.getProcessInstId();
				if (contractPart.getSupplierCode()!=null){
					contractCode = contractPart.getSupplierCode();
				}
			}
			map.put("contract", contractPart);
		} else if (contractType.equals("备泵合同")) {
			
			ContractPump contractPump = null;
			if (contractId != null && !contractId.equals("")) {
				contractPump = contractService.getContractPumpById(contractId);
				pInstId=contractPump.getProcessInstId();
				if (contractPump.getSupplierCode()!=null){
					contractCode = contractPump.getSupplierCode();
				}
			}
			map.put("contract", contractPump);
		} else if (contractType.equals("维修合同")) {
		
			ContractRepair contractRepair = null;
			if (contractId != null && !contractId.equals("")) {
				contractRepair = contractService.getContractRepairById(contractId);
				pInstId=contractRepair.getProcessInstId();
				if (contractRepair.getSupplierCode()!=null){
					contractCode = contractRepair.getSupplierCode();
				}
			}
			map.put("contract", contractRepair);
		} else {
			Contract contract = null;
			if (contractId != null && !contractId.equals("")) {
				contract = contractService.getContractById(contractId);
				pInstId=contract.getProcessInstId();
				if (contract.getSupplierCode()!=null){
					contractCode = contract.getSupplierCode();
				}
			}
			map.put("contract", contract);

		}
		List<QuoteDevice> quoteDevices = contractService.getDevices(0, Integer.MAX_VALUE, contractId, null, null);
		List<QuoteReplacement> quoteReplacements = contractService.getReplacements(0,  Integer.MAX_VALUE, contractId,  "createTime", "desc");
		map.put("pumps", quoteDevices);
		map.put("others", quoteReplacements);
		map.put("taskId", taskId);
		map.put("auditNodes", auditNodeService.getAll(pInstId,contractId));

		return map;
	}
	
	/**
	 * 获得下拉框选项
	 */
	private ModelAndView getSelect(String contractType, ModelAndView modelAndView) {
		String stopGroup = "货物到站";
		String industryInfoGroup = "行业";
		String dutyAreaGroup = "责任区域";
		String southNorthAreaGroup = "南北片区";
		String checkKindGroup = "考核分类";
		String productKindGroup = "产品分类";
		String productTypeGroup = "产品类型";
		Account a = this.getMyAccount();
		String userId = a.getUser().getId();
		String userName = a.getUser().getName();
		String superior = a.getUser().getSaleArea().getSuperior();
		/*String dutyOfficerGroup = "责任人";
		String signOfficerGroup = "合同签订人";
		String repairOfficerGroup = "维修协议人";
		String quotationOfficerGroup = "报价人";
		String head = "处长";
		String deputyHead = "副处长";
		String manager = "片区经理";
		String workOutside = "销售外勤";
		String workInside = "销售内勤";
		if (superior!=null && !superior.equals("")){
			head = superior.substring(0, 2) + head;
			deputyHead = superior.substring(0, 2) + deputyHead;
			manager = superior.substring(0, 2) + manager;
		}
		List<Object> signOfficers = new ArrayList<Object>();
		List<Object> workInsides = contractService.getUserNamesByroleName(workInside);
		List<Object> workOutsides = contractService.getUserNamesByroleName(workOutside);
		if (contractType.equals("备件合同")){
			for (Object name : workInsides){
				signOfficers.add(name);
			}
			for (Object name : workOutsides){
				signOfficers.add(name);
			}
		} else{
			signOfficers = workOutsides;
		}*/
		if (contractType.equals("维修合同")){
			String repairKindGroup = "返修类别";
			modelAndView.addObject("repairKinds", optionService.getRepository().findByGroup(repairKindGroup));
		}
		List<User> allSuperiorMen = contractService.getAllSuperiorMenBySuperior(superior);
		modelAndView.addObject("allSuperiorMen", allSuperiorMen);
		modelAndView.addObject("contractType", contractType);
		modelAndView.addObject("userId", userId);
		modelAndView.addObject("userName", userName);
		modelAndView.addObject("superior", superior);
		modelAndView.addObject("areas", contractService.getAreasBySuperior(superior));
		modelAndView.addObject("stops", optionService.getRepository().findByGroup(stopGroup));
		modelAndView.addObject("orderAreas", contractService.getSuperiorAreasBySuperior(superior));
		modelAndView.addObject("industryInfos", optionService.getRepository().findByGroup(industryInfoGroup));
		modelAndView.addObject("dutyAreas", optionService.getRepository().findByGroup(dutyAreaGroup));
		modelAndView.addObject("southNorthAreas", optionService.getRepository().findByGroup(southNorthAreaGroup));
		modelAndView.addObject("checkKinds", optionService.getRepository().findByGroup(checkKindGroup));
		modelAndView.addObject("productKinds", optionService.getRepository().findByGroup(productKindGroup));
		modelAndView.addObject("productTypes", optionService.getRepository().findByGroup(productTypeGroup));
		modelAndView.addObject("operatDate", new Date());
		String businessGroup = "行业";
		String regionGroup = "地区";
		String buyerGroup = "买方属性";
		String asset = "资产性质";
		String continuelife = "续存年限";
		String credit = "支付信用";
		String period = "合作期限";
		String customerCode=customerService.getCustomerCode();
		modelAndView.addObject("customerCode", customerCode);
		modelAndView.addObject("saleAreas", saleAreaService.getRepository().findBySuperior(superior));
		modelAndView.addObject("businesses", optionService.getRepository().findByGroup(businessGroup));
		modelAndView.addObject("regions", optionService.getRepository().findByGroup(regionGroup));
		modelAndView.addObject("buyers", optionService.getRepository().findByGroup(buyerGroup));
		modelAndView.addObject("assets", optionService.getRepository().findByGroup(asset));
		modelAndView.addObject("continuelifes", optionService.getRepository().findByGroup(continuelife));
		modelAndView.addObject("credits", optionService.getRepository().findByGroup(credit));
		modelAndView.addObject("periods", optionService.getRepository().findByGroup(period));
		modelAndView.addObject("customers", customerService.getRepository().findAll());
		/*modelAndView.addObject("dutyOfficers", optionService.getRepository().findByGroup(dutyOfficerGroup));
		modelAndView.addObject("dutyOfficers", contractService.getDutyOfficersByroleName(head, deputyHead, manager));
		modelAndView.addObject("signOfficers", optionService.getRepository().findByGroup(signOfficerGroup));
		modelAndView.addObject("repairOfficers", optionService.getRepository().findByGroup(repairOfficerGroup));
		modelAndView.addObject("quotationOfficers", optionService.getRepository().findByGroup(quotationOfficerGroup));
		modelAndView.addObject("signOfficers", signOfficers);
		modelAndView.addObject("quotationOfficers", workOutsides);*/
		return modelAndView;
	}

	/**
	 * 数据提交前验证供方合同号是否唯一
	 */
	@RequestMapping(value = "/validSupplierCode/{id}/{code}", method = RequestMethod.GET)
	public Map<String, Object> validSupplierCode(@PathVariable String id, @PathVariable String code,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String codeState = "0";
		if (!StringUtils.hasText(id)) {
			id = "0";
		}
		int c = 0;
		// 得到除去该合同供方合同号也为supplierCode的条数；
		if (StringUtils.hasText(code)) {
			c = contractService.getContractInfosCountBySupplierCode(id, code);
			if (c > 0) {
				codeState = "1";
			}
		}
		map.put("codeState", codeState);
		return map;
	}
	
	/**
	 * 项目合同验证总价是否不小于总的划分金额
	 */
	@RequestMapping(value = "/validTotalSum/{id}/{sum}/{type}", method = RequestMethod.GET)
	public Map<String, Object> validTotalSum(@PathVariable String id, @PathVariable float sum, 
			@PathVariable String type, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String sumState = "1";
		//当合同还未保存时（没有合同id），js中会给其一个字符串"null"，因为此时还没有占比划分，直接验证通过
		if (id.equals("null")){
			sumState = "0";
		} else if (StringUtils.hasText(id)) {
			Contract contract = contractService.getRepository().findOne(id);
			if (contract != null){
				float allScaleDivide = contractService.getAllScaleDivide(id);
				if (type.equals("0")) {// 保存合同
					if (sum >= (allScaleDivide)) {
						sumState = "0";// 金额大小满足规则
					}
				} else if (type.equals("1")) {// 保存占比划分
					double totalSum = contract.getTotalSum();
					if (totalSum >= (allScaleDivide + sum)) {
						sumState = "0";// 金额大小满足规则
					}
				}
			}
		}
		map.put("sumState", sumState);
		return map;
	}

	/**
	 * 保存项目合同，返回合同id,createTime,type
	 */
	@RequestMapping(value = "saveContract", method = RequestMethod.POST)
	public Map<String, Object> saveContract(@RequestBody Contract contract, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		int reaslt = 0;
		if (contract != null){
			User oldUser = saveContractLog(contract);
			if (oldUser != null){
				contract.setUser(oldUser);
			}
			contract.setAuditState("通过");
			contractService.getRepository().save(contract);
			ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingService.getExdeSchedulingRepository().findBycontractId(contract.getId(), "项目合同");
			if(exdeTbOPPlanTask != null){
				String[] ids = {exdeTbOPPlanTask.getId()};
				reaslt = exdeSchedulingService.updateExdeTbOPPlanTask(ids, user);
			}
			map.put("contractId", contract.getId());
			map.put("createTime", contract.getCreateTime());
			map.put("contractType", contract.getContractType());
			map.put("reaslt", reaslt);
		}
		return map;
	}

	/**
	 * 保存备件合同，返回合同id,createTime,type
	 */
	@RequestMapping(value = "saveContractPart", method = RequestMethod.POST)
	public Map<String, Object> saveContractPart(@RequestBody ContractPart contractPart, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		int reaslt = 0;
		if (contractPart != null){
			User oldUser = saveContractLog(contractPart);
			if (oldUser != null){
				contractPart.setUser(oldUser);
			}
			contractPart.setAuditState("通过");
			contractService.getRepository2().save(contractPart);
			ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingService.getExdeSchedulingRepository().findBycontractId(contractPart.getId(), "备件合同");
			if(exdeTbOPPlanTask != null){
				String[] ids = {exdeTbOPPlanTask.getId()};
				reaslt = exdeSchedulingService.updateExdeTbOPPlanTask(ids, user);
			}
			String contractId=contractPart.getId();
			String contractType=contractPart.getContractType();
			String quoteId=request.getParameter("quoteId");
			if(quoteId!=null&&!"null".equals(quoteId)){
				List<QuoteReplacement> cs=contractService.getRepository9().findByContractIDOrderByIndexOrderDesc(contractId);
				int n=cs.size()+1;
				if(!cs.isEmpty()){
					n=cs.get(0).getIndexOrder()+1;
				}
				List<QuoteReplacement> qs=contractService.getRepository9().findByQuote_Id(quoteId);
				
				
				List<QuoteReplacement> news=new ArrayList<>();
				for(QuoteReplacement q:qs){
					QuoteReplacement newQ=new QuoteReplacement();
					BeanUtils.copyProperties(q, newQ,"id","quote","costPrice");
					newQ.setQuote(null);
					newQ.setIndexOrder(n);
					newQ.setContractID(contractId);
					newQ.setnOneDiscount(q.getPrice());
					newQ.setPrice(q.getAmount() * q.getPrice());
					newQ.setContractType(contractType);
					news.add(newQ);
					n++;
				}
				contractService.getRepository9().save(news);
				
			}
			
			
			map.put("contractId", contractPart.getId());
			map.put("createTime", contractPart.getCreateTime());
			map.put("contractType", contractPart.getContractType());
			map.put("reaslt", reaslt);
		}
		return map;
	}
	/**
	 * 保存备件合同，返回合同id,createTime,type
	 */
	@RequestMapping(value = "upordown", method = RequestMethod.GET)
	public Map<String, Object> upordown(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		//Account a = this.getMyAccount();
		//User user = a.getUser();
		String contractId = request.getParameter("contractId");
		double ratio = Double.valueOf(request.getParameter("ratio"));
		ContractPart contractPart = contractService.getRepository2().findOne(contractId);
		contractPart.setTotalSum((float)(contractPart.getTotalSum()*(1+ratio/100)));
		contractService.getRepository2().save(contractPart);
		if(contractId!=null&&!"null".equals(contractId)){
			List<QuoteReplacement> qs=contractService.getRepository9().findByContractID(contractId);
			for(QuoteReplacement q:qs){
				q.setnOneDiscount((float)(q.getnOneDiscount()*(1+ratio/100)));
				q.setPrice((float)(q.getPrice()*(1+ratio/100)));
			}
			contractService.getRepository9().save(qs);
		}
		return map;
	}

	/**
	 * 保存备泵合同，返回合同id,createTime,type
	 */
	@RequestMapping(value = "saveContractPump", method = RequestMethod.POST)
	public Map<String, Object> saveContractPump(@RequestBody ContractPump contractPump, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		int reaslt = 0;
		if (contractPump != null){
			User oldUser = saveContractLog(contractPump);
			if (oldUser != null){
				contractPump.setUser(oldUser);
			}
			contractPump.setAuditState("通过");
			contractService.getRepository3().save(contractPump);
			ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingService.getExdeSchedulingRepository().findBycontractId(contractPump.getId(), "备泵合同");
			if(exdeTbOPPlanTask != null){
				String[] ids = {exdeTbOPPlanTask.getId()};
				reaslt = exdeSchedulingService.updateExdeTbOPPlanTask(ids, user);
			}
			map.put("contractId", contractPump.getId());
			map.put("createTime", contractPump.getCreateTime());
			map.put("contractType", contractPump.getContractType());
			map.put("reaslt", reaslt);
		}
		return map;
	}

	/**
	 * 保存维修合同，返回合同id,createTime,type
	 */
	@RequestMapping(value = "saveContractRepair", method = RequestMethod.POST)
	public Map<String, Object> saveContractRepair(@RequestBody ContractRepair contractRepair,
			HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Account a = this.getMyAccount();
		User user = a.getUser();
		int reaslt = 0;
		if (contractRepair != null){
			User oldUser = saveContractLog(contractRepair);
			if (oldUser != null){
				contractRepair.setUser(oldUser);
			}
			contractRepair.setAuditState("通过");
			contractService.getRepository4().save(contractRepair);
			ExdeTbOPPlanTask exdeTbOPPlanTask = exdeSchedulingService.getExdeSchedulingRepository().findBycontractId(contractRepair.getId(), "维修合同");
			if(exdeTbOPPlanTask != null){
				String[] ids = {exdeTbOPPlanTask.getId()};
				reaslt = exdeSchedulingService.updateExdeTbOPPlanTask(ids, user);
			}
			map.put("contractId", contractRepair.getId());
			map.put("createTime", contractRepair.getCreateTime());
			map.put("contractType", contractRepair.getContractType());
			map.put("reaslt", reaslt);
		}
		return map;
	}
	
	/**
	 * 保存合同时新增日志记录,返回User用于维护该字段
	 * @return 
	 */
	private User saveContractLog(Root root) {
		Account a = this.getMyAccount();
		User user = a.getUser();
		String contractId = "";
		String contractType = "";
		String supplierCode = "";
		double totalSum = 0;
		User oldUser = null;
		String oldSupplierCode = "";
		double oldTotalSum = 0;
		Boolean isEdit = false;//是否是编辑,等于true时为编辑;
		String auditState = "通过";//合同审批状态
		if (root instanceof Contract) {
			Contract contract = (Contract) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			totalSum = contract.getTotalSum();
			Contract old = contractService.getRepository().findOne(contractId);
			if (old!=null){
				isEdit = true;
				oldUser = old.getUser();
				oldSupplierCode = old.getSupplierCode();
				oldTotalSum = old.getTotalSum();
				auditState = old.getAuditState();
			}
		} else if (root instanceof ContractPart) {
			ContractPart contract = (ContractPart) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			totalSum = contract.getTotalSum();
			ContractPart old = contractService.getRepository2().findOne(contractId);
			if (old!=null){
				isEdit = true;
				oldUser = old.getUser();
				oldSupplierCode = old.getSupplierCode();
				oldTotalSum = old.getTotalSum();
				auditState = old.getAuditState();
			}
		} else if (root instanceof ContractPump) {
			ContractPump contract = (ContractPump) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			totalSum = contract.getTotalSum();
			ContractPump old = contractService.getRepository3().findOne(contractId);
			if (old!=null){
				isEdit = true;
				oldUser = old.getUser();
				oldSupplierCode = old.getSupplierCode();
				oldTotalSum = old.getTotalSum();
				auditState = old.getAuditState();
			}
		} else if (root instanceof ContractRepair) {
			ContractRepair contract = (ContractRepair) root;
			contractId = contract.getId();
			contractType = contract.getContractType();
			supplierCode = contract.getSupplierCode();
			totalSum = contract.getTotalSum();
			ContractRepair old = contractService.getRepository4().findOne(contractId);
			if (old!=null){
				isEdit = true;
				oldUser = old.getUser();
				oldSupplierCode = old.getSupplierCode();
				oldTotalSum = old.getTotalSum();
				auditState = old.getAuditState();
			}
		}
		if(isEdit){
			String content  = "编辑【" + contractType + "】【" + oldSupplierCode + "】";
			//if (!auditState.equals("未提交")){
				if (!supplierCode.equals(oldSupplierCode)){
					content += ",供方合同号从【" + oldSupplierCode + "】更改为【" + supplierCode + "】";
				}
				if (totalSum!=oldTotalSum){
					content += ",总价从" + oldTotalSum + "更改为" + totalSum + "";
				}
			//}
			operateLogService.log(user, "编辑合同", content);
		}else{
			String content  = "新增【" + contractType + "】【" + supplierCode + "】";
			operateLogService.log(user, "新增合同", content);
		}
		return oldUser;
	}

	/**
	 * 通过项目合同供方合同号得到合同信息
	 */
	@RequestMapping(value = "getContractBySupplierCode", method = RequestMethod.GET)
	public Map<String, Object> getContractBySupplierCode(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String supplierCode = request.getParameter("supplierCode");
		Contract contract = new Contract();
		if (StringUtils.hasText(supplierCode)) {
			contract = contractService.getContractBySupplierCode(supplierCode);
		}
		map.put("contract", contract);
		return map;
	}

	/**
	 * 项目合同占比划分显示
	 */
	@RequestMapping(value = "getDivideScale", method = RequestMethod.GET)
	public Map<String, Object> getDivideScale(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		/*int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));*/
		String contractId = request.getParameter("contractId");
		if (contractId == null) {
			contractId = "";
		}
		List<DivideScale> divideScales = contractService.getContractDivideScales(1, 10, contractId, null, null);
		Long count = (long) contractService.getContractDivideScalesCount(contractId);
		map.put("data", divideScales);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 删除项目合同占比划分
	 */
	@RequestMapping(value = "deleteDivideScale", method = RequestMethod.GET)
	public Map<String, Object> deleteDivideScale(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		if (StringUtils.hasText(ids)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			String[] divideScaleIds = ids.split(",");
			for (String id : divideScaleIds){
				DivideScale oldD = contractService.getRepository1().findOne(id);
				if (oldD!=null){
					String code = "";
					Contract oldC = contractService.getRepository().findOne(oldD.getContractID());
					if (oldC!=null){
						code = oldC.getSupplierCode();
					}
					String content  = "删除【项目合同】【" + code + "】占比划分负责人【" + oldD.getFunctionary() + "】";
					operateLogService.log(user, "删除合同占比划分", content);
				}
			}
			contractService.deleteDivideScale(ids);
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * (备件、备泵、维修)合同已关联合同数据显示
	 */
	@RequestMapping(value = "getRelevanceContract", method = RequestMethod.GET)
	public Map<String, Object> getRelevanceContract(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String contractId = request.getParameter("contractId");
		if (contractId == null) {
			contractId = "";
		}
		List<Contract> contracts = contractService.getRelevanceContracts(start, length, contractId, null, null);
		Long count = (long) contractService.getRelevanceContractsCount(contractId);
		map.put("data", contracts);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * (项目、备泵、维修)合同细目泵数据显示
	 */
	@RequestMapping(value = "getDevice", method = RequestMethod.GET)
	public Map<String, Object> getDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String contractId = request.getParameter("contractId");
		if (contractId == null) {
			contractId = "";
		}
		List<QuoteDevice> quoteDevices = contractService.getDevices(start, length, contractId, null, null);
		Long count = (long) contractService.getDevicesCount(contractId);
		map.put("data", quoteDevices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 删除(项目、备泵、维修)合同细目泵
	 */
	@RequestMapping(value = "deleteDevice", method = RequestMethod.GET)
	public Map<String, Object> deleteDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		if (StringUtils.hasText(ids)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			String[] deviceIds = ids.split(",");
		
			
			for (String id : deviceIds){
				QuoteDevice quoteDevice = contractService.getRepository5().findOne(id);
				if (quoteDevice!=null){
					String cId = quoteDevice.getContractID();
					String cType = quoteDevice.getContractType();
					String cCode = contractService.getSupplierCodeByTypeAndId(cType, cId);
					String typeContent = "";
					if (quoteDevice.getSubDivideType()!=null&&!quoteDevice.getSubDivideType().equals("")){
						typeContent = "【" + quoteDevice.getSubDivideType() + "】";
					}
					String content  = "删除【" + cType + "】【" + cCode + "】"
							+ "细目主机【" + quoteDevice.getProductType() + "】" + typeContent + ""
									+ "【" + quoteDevice.getProductName() + "】";
					operateLogService.log(user, "删除合同主机", content);
				}
			}
			contractService.deleteDevice(ids);
			
			
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 新建/编辑(项目、备泵、维修)合同细目单个泵
	 */
	@RequestMapping(value = "editOneDevice", method = RequestMethod.POST)
	public Map<String, Object> editOneDevice(@RequestBody QuoteDevice quoteDevice, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		if (quoteDevice != null) {
			boolean isEdit = false;
			QuoteDevice old = contractService.getRepository5().findOne(quoteDevice.getId());
			if (old!=null){
				isEdit = true;
			}
			contractService.editOneDevice(quoteDevice);
			Account a = this.getMyAccount();
			User user = a.getUser();
			String cId = quoteDevice.getContractID();
			String cType = quoteDevice.getContractType();
			String cCode = contractService.getSupplierCodeByTypeAndId(cType, cId);
			String typeContent = "";
			if (quoteDevice.getSubDivideType()!=null&&!quoteDevice.getSubDivideType().equals("")){
				typeContent = "【" + quoteDevice.getSubDivideType() + "】";
			}
			if(isEdit){
				String content  = "编辑【" + cType + "】【" + cCode + "】"
						+ "细目主机【" + quoteDevice.getProductType() + "】" + typeContent + ""
								+ "【" + quoteDevice.getProductName() + "】";
				operateLogService.log(user, "编辑合同主机", content);
			}else{
				String content  = "新增【" + cType + "】【" + cCode + "】"
						+ "细目主机【" + quoteDevice.getProductType() + "】" + typeContent + ""
								+ "【" + quoteDevice.getProductName() + "】";
				operateLogService.log(user, "新增合同主机", content);
			}
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 批量编辑(备泵、维修)合同细目泵(项目合同细目泵不支持批量编辑)
	 */
	@RequestMapping(value = "editMoreDevice", method = RequestMethod.GET)
	public Map<String, Object> editMoreDevice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String deviceInfo = request.getParameter("deviceInfo");
		if (StringUtils.hasText(deviceInfo)) {
			contractService.editMoreDevice(deviceInfo);
			Account a = this.getMyAccount();
			User user = a.getUser();
			String[] params = deviceInfo.split(":");// params[0]是id数据;params[1]是需要关联的项目合同供方合同号
			if (params.length == 2) {
				String[] QuoteDeviceIds = params[0].split(",");
				String contractID = params[1];
				Contract contract = null;
				String deviceContent = "";
				String code = "";
				if (StringUtils.hasText(contractID)) {
					contract = contractService.getRepository().findOne(contractID);
					if (contract!=null){
						code = contract.getSupplierCode();
					}
				}
				for (String id : QuoteDeviceIds){
					QuoteDevice quoteDevice = contractService.getRepository5().findOne(id);
					String typeContent = "";
					if (quoteDevice.getSubDivideType()!=null&&!quoteDevice.getSubDivideType().equals("")){
						typeContent = "【" + quoteDevice.getSubDivideType() + "】";
					}
					if (quoteDevice!=null){
						deviceContent += "【" + quoteDevice.getProductType() + "】" + typeContent + ""
								+ "【" + quoteDevice.getProductName() + "】，";
					}
				}
				if (!deviceContent.equals("")){
					deviceContent = deviceContent.substring(0, deviceContent.length()-1);
				}
				String content  = "批量编辑细目主机【" + deviceContent + "】关联到项目合同【" + code + "】";
				operateLogService.log(user, "批量编辑合同主机", content);
			}
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * (项目、维修)合同细目其他及备件合同细目数据显示
	 */
	@RequestMapping(value = "getReplacement", method = RequestMethod.GET)
	public Map<String, Object> getReplacement(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		int start = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String contractId = request.getParameter("contractId");
		if (contractId == null) {
			contractId = "";
		}
		List<QuoteReplacement> replacementDevices = contractService.getReplacements(start, length, contractId, null,
				null);
		Long count = (long) contractService.getReplacementsCount(contractId);
		map.put("data", replacementDevices);
		map.put("draw", request.getParameter("draw"));
		map.put("recordsFiltered", count);
		map.put("recordsTotal", count);
		return map;
	}

	/**
	 * 删除(项目、备件、维修)合同细目配件
	 */
	@RequestMapping(value = "deleteReplacement", method = RequestMethod.GET)
	public Map<String, Object> deleteReplacement(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		if (StringUtils.hasText(ids)) {
			Account a = this.getMyAccount();
			User user = a.getUser();
			String[] replacementIds = ids.split(",");
			
			QuoteReplacement q=contractService.getRepository9().findOne(replacementIds[0]);
			int order=q.getIndexOrder();
			String contractID= q.getContractID();
			for (String id : replacementIds){
				QuoteReplacement quoteReplacement = contractService.getRepository9().findOne(id);
				if (quoteReplacement!=null){
					String cId = quoteReplacement.getContractID();
					String cType = quoteReplacement.getContractType();
					String cCode = contractService.getSupplierCodeByTypeAndId(cType, cId);
					String content  = "删除【" + cType + "】【" + cCode + "】"
							+ "细目配件【" + quoteReplacement.getType() + "】【" + quoteReplacement.getDeviceName() + "】";
					operateLogService.log(user, "删除合同配件", content);
				}
			}
			contractService.deleteReplacement(ids);
			
			//更新
			List<QuoteReplacement>qs=contractService.getRepository9().findByContractIDAndIndexOrderGreaterThanEqualOrderByIndexOrderAsc(contractID, order);
			for(int i=0;i<qs.size();i++){
				qs.get(i).setIndexOrder(order);
				order++;
			}
			
			contractService.getRepository9().save(qs);
			
		}
		map.put("code", 0);
		return map;
	}
	
	
	/**
	 * 清空含税单价总价
	 */
	@RequestMapping(value = "clearPrice", method = RequestMethod.GET)
	public Map<String, Object> clearPrice(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String ids = request.getParameter("ids");
		
		String[] idArray=ids.split(",");
		List<QuoteReplacement>qs=new ArrayList<>();
		for(String id:idArray){
			QuoteReplacement q=this.contractService.getRepository9().findOne(id);
			q.setnOneDiscount((float)0);
			q.setPrice((float) 0);
			qs.add(q);
		}
		this.contractService.getRepository9().save(qs);
		map.put("code", 0);
		return map;
	}
	
	/**
	 * 修改备件合同细目顺序
	 */
	@RequestMapping(value = "changeReplaceIndex", method = RequestMethod.GET)
	public Map<String, Object> changeReplaceIndex(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");
		int oldIndexOrder = Integer.valueOf(request.getParameter("oldIndexOrder"));
		String contractID = request.getParameter("contractID");
		int changeNum = Integer.valueOf(request.getParameter("changeNum"));
		int nowIndex=oldIndexOrder+changeNum;
		QuoteReplacement nowChange=this.contractService.getRepository9().findOne(id);
		QuoteReplacement preChange=this.contractService.getRepository9().findByContractIDAndIndexOrder(contractID,nowIndex);
		if(null!=preChange){
			nowChange.setIndexOrder(nowIndex);
			preChange.setIndexOrder(oldIndexOrder);
			this.contractService.getRepository9().save(nowChange);
			this.contractService.getRepository9().save(preChange);
		}
		map.put("code", 0);
		return map;
	}

	
	
	
	
	/**
	 * 新建/编辑(项目、备件、维修)合同细目单个配件
	 */
	@RequestMapping(value = "editOneReplacement", method = RequestMethod.POST)
	public Map<String, Object> editOneReplacement(@RequestBody QuoteReplacement quoteReplacement,
			HttpServletRequest request) {
		
		
		Map<String, Object> map = new HashMap<String, Object>();
		if (quoteReplacement != null) {
			
			boolean isEdit = false;
			QuoteReplacement old = contractService.getRepository9().findOne(quoteReplacement.getId());
			if (old!=null){
				isEdit = true;
			}
			contractService.editOneReplacement(quoteReplacement);
			Account a = this.getMyAccount();
			User user = a.getUser();
			String cId = quoteReplacement.getContractID();
			String cType = quoteReplacement.getContractType();
			String cCode = contractService.getSupplierCodeByTypeAndId(cType, cId);
			if(isEdit){
				String content  = "编辑【" + cType + "】【" + cCode + "】"
						+ "细目配件【" + quoteReplacement.getType() + "】【" + quoteReplacement.getDeviceName() + "】";
				operateLogService.log(user, "编辑合同主机", content);
			}else{
				String content  = "新增【" + cType + "】【" + cCode + "】"
						+ "细目配件【" + quoteReplacement.getType() + "】【" + quoteReplacement.getDeviceName() + "】";
				operateLogService.log(user, "新增合同主机", content);
			}
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 批量编辑(备件、维修)合同细目备件(项目合同细目配件不支持批量编辑)
	 */
	@RequestMapping(value = "editMoreReplacement", method = RequestMethod.GET)
	public Map<String, Object> editMoreReplacement(HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String replacementInfo = request.getParameter("replacementInfo");
		if (StringUtils.hasText(replacementInfo)) {
			contractService.editMoreReplacement(replacementInfo);
			Account a = this.getMyAccount();
			User user = a.getUser();
			String[] params = replacementInfo.split(":");// params[0]是id数据;params[1]是需要关联的项目合同供方合同号
			if (params.length == 2) {
				String[] QuoteReplacementIds = params[0].split(",");
				String contractID = params[1];
				Contract contract = null;
				String replacementContent = "";
				String code = "";
				if (StringUtils.hasText(contractID)) {
					contract = contractService.getRepository().findOne(contractID);
					if (contract!=null){
						code = contract.getSupplierCode();
					}
				}
				for (String id : QuoteReplacementIds){
					QuoteReplacement quoteReplacement = contractService.getRepository9().findOne(id);
					if (quoteReplacement!=null){
						replacementContent += "【" + quoteReplacement.getType() + "】【" + quoteReplacement.getDeviceName() + "】，";
					}
				}
				if (!replacementContent.equals("")){
					replacementContent = replacementContent.substring(0, replacementContent.length()-1);
				}
				String content  = "批量编辑细目配件【" + replacementContent + "】关联到项目合同【" + code + "】";
				operateLogService.log(user, "批量编辑合同配件", content);
			}
		}
		map.put("code", 0);
		return map;
	}

	/**
	 * 得到产品类型和细分类型下拉框选项
	 */
	@RequestMapping(value = "getDeviceOption/{productType}", method = RequestMethod.GET)
	public Map<String, Object> getDeviceOption(@PathVariable String productType, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		String subDivideTypeGroup = productType;
		List<Option> subDivideTypes = optionService.getRepository().findByGroup(subDivideTypeGroup);
		List<String> options = new ArrayList<String>();
		if (subDivideTypes.size() > 0) {
			for (Option subDivideType : subDivideTypes) {
				options.add(subDivideType.getTitle());
			}
		}
		map.put("options", options);
		return map;
	}

	/**
	 * EXCEL导入处理
	 */
	@RequestMapping(value = "import/{contractId}/{type}", method = RequestMethod.POST)
	public Map<String, Object> importExcel(@PathVariable String contractId, @PathVariable String type,
			@RequestParam("file") MultipartFile file, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {

		Map<String, Object> map = new HashMap<String, Object>();

		int code = -1;
		long count = -1;

		String saveFileName = attachmentService.upload(file);

		// 文件传后，再读取EXCEL写入数据库
		if (StringUtils.hasText(saveFileName)) {
			count = contractService.importExcel(saveFileName, contractId, type);
			code = 0;
		}

		if (code == 0){
			Account a = this.getMyAccount();
			User user = a.getUser();
			String cType = "项目合同";
			String qType = "主机";
			switch (type) {
			case "0":
				qType = "配件";
				break;
			case "2":
				qType = "配件";
				cType = "维修合同";
				break;
			case "3":		
				cType = "维修合同";
				break;
			case "4":
				qType = "备件";
				cType = "备件合同";
				break;
			case "5":	
				qType = "备泵";
				cType = "备泵合同";
				break;
			}
			String cCode = contractService.getSupplierCodeByTypeAndId(cType, contractId);
			String content  = "【" + cType + "】【" + cCode + "】导入细目【" + qType + "】";
			operateLogService.log(user, "导入合同细目", content);
		}
		map.put("code", code);
		map.put("count", count);
		return map;
	}

	/**
	 * 提交合同审批
	 * 
	 * @param quoteId
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/audit/{contractId}/{contractType}", method = RequestMethod.POST)
	public Map<String, Object> submitAudit(@PathVariable String contractId, @PathVariable String contractType,
			HttpServletRequest request) {

		Map<String, Object> map = new HashMap<>();
		Map<String, String> variables = new HashMap<>();
		Account account = this.getMyAccount();
		int code = -1;

		String auditorNumber = request.getParameter("auditorNumber");
		String auditor1 = request.getParameter("auditor1");
		String auditor2 = request.getParameter("auditor2");
		String auditor3 = request.getParameter("auditor3");
		String auditor4 = request.getParameter("auditor4");
		String auditor5 = request.getParameter("auditor5");
		String auditor6 = request.getParameter("auditor6");
		String auditor7 = request.getParameter("auditor7");
		String auditor8 = request.getParameter("auditor8");

		if (null != contractId && null != account && null != auditorNumber) {
			// 放置流程实例变量
			variables.put("starter", account.getUser().getId());
			variables.put("auditor1", auditor1);
			variables.put("auditor2", auditor2);
			variables.put("auditor3", auditor3);
			variables.put("auditor4", auditor4);
			variables.put("auditor5", auditor5);
			variables.put("auditor6", auditor6);
			variables.put("auditor7", auditor7);
			variables.put("auditor8", auditor8);

			variables.put("auditorNumber", auditorNumber);
			variables.put("auditState", "已提交");
			variables.put("entityName", "contract");
			variables.put("processDefinitionName", contractType);

			variables.put("entityId", contractId);
			variables.put("contractType", contractType);

			ProcessInstance pInst = activitiService.startProcessInstance("bid", account.getUser().getId(), variables);
			// 流程启动后，将其实例相关信息保存到业务实体中，以便查询
			contractService.saveProcessStart(contractId, contractType, pInst);
			code = 0;

		}
		map.put("code", code);
		return map;
	}
	//导出选择项
		@RequestMapping(value = "/exportSelects/{key}", method = RequestMethod.GET)
		@ResponseBody
		public ResponseEntity<org.springframework.core.io.Resource> exportSelects(@PathVariable String key, HttpServletRequest request)
				throws UnsupportedEncodingException {	
			String id[] = key.split(",");
			System.out.println(id[0]);
			List<ContractInfo> contracts = new ArrayList<ContractInfo>();
			for (int i = 0; i < id.length; i++) {
				String contractId = id[i];
				ContractInfo d=contractService.getRepository().getContractInfoById(contractId);
				contracts.add(d);
				System.out.println(contracts.get(i).getContractId());
			}
			return this.excelService.toExcel(contracts, "合同信息.xlsx");
		}
		
		/**导出合同
		 * @param key 组合id
		 * @return
		 * @throws UnsupportedEncodingException
		 */
		@RequestMapping(value = "/export/{key}", method = RequestMethod.GET)
		public ResponseEntity<org.springframework.core.io.Resource> excelFile(@PathVariable String key)
				throws UnsupportedEncodingException {
			String ids=key;
			String id[] = ids.split(",");
			List<String>idAll=new ArrayList<>();
			for(String i:id){
				idAll.add(i);
			}
			List<ContractInfo>contracts=contractService.getContractInfoRepository().findAll(idAll);
			return this.excelService.toExcel(contracts, "合同信息.xlsx");
		}
		
//		//导出搜索所得结果项，关键字为空时，导出全部
//		@RequestMapping(value = "/export/{key}", method = RequestMethod.GET)
//		@ResponseBody
//		public ResponseEntity<org.springframework.core.io.Resource> excelFile(@PathVariable String key, HttpServletRequest request)
//				throws UnsupportedEncodingException {
//			Map<String, String> condition = new HashMap<String, String>();
//			Account a = this.getMyAccount();
//			String userId = a.getUser().getId();
//			String superior = a.getUser().getSaleArea().getSuperior();
//			String areaName = a.getUser().getSaleArea().getAreaName();
//			String name = "contractInfo";
//			Module module = this.getPageModule(name);
//			String dataFilter = module.getDataFilter();
//			if (key.equals("null")) {
//				key = "";
//			}
//			key = key.replaceAll("\\s+", "");
//			if (userId == null) {
//				userId = "";
//			}
//			if (superior == null) {
//				superior = "";
//			}
//			if (areaName == null) {
//				areaName = "";
//			}
//			if (dataFilter == null) {
//				dataFilter = "";
//			}
//			condition.put("key", key);
//			condition.put("userId", userId);
//			condition.put("superior", superior);
//			condition.put("areaName", areaName);
//			condition.put("dataFilter", dataFilter);
//			List<ContractInfo> contracts = contractService.getContractInfos(0, Integer.MAX_VALUE, condition, null, null);
//			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");  
//			for(int i=0;i<contracts.size();i++)
//			{
//				String str=sdf.format(contracts.get(i).getSignedDate());  
//			}
//			return this.excelService.toExcel(contracts, "合同信息.xlsx");
//		}
		
		
		@RequestMapping(value="/exportByKey",method=RequestMethod.GET)
		public Map<String, Object>exportExcelFile(HttpServletRequest request){
			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> qMap = new HashMap<String, Object>();
			Map<String, Object> condition = new HashMap<String, Object>();
			Map<String, Object>numMap=new HashMap<String, Object>();
			int start = 0;
			Account a = this.getMyAccount();
			Module module = this.getPageModule("contractInfo");
			String dataFilter = module.getDataFilter();
			User user = a.getUser();
			this.getQueryParams(qMap,numMap);
			condition.put("dataFilter", dataFilter);
			condition.put("qMap", qMap);
			condition.put("numMap", numMap);
			List<ContractInfo> contracts = contractService.getQueryContractsHql(start, Integer.MAX_VALUE, condition, user, "createTime",
					"desc");
			if(!contracts.isEmpty()){
				map.put("contracts",contracts);
				return map;
			}
			return map;
		}
		
		//校验金额
		@RequestMapping(value="/checkMoney",method=RequestMethod.GET)
		public int checkMoney(HttpServletRequest request){
			double sum = 0;
			double totalSum = Double.valueOf(request.getParameter("totalSum"));
			String contractId = request.getParameter("contractId");
			if (contractId == null) {
				contractId = "";
			}
			//ContractInfo contractInfo = contractService.getContractInfoRepository().findOne(contractId);
			List<QuoteDevice> quoteDevices = contractService.getDevices(0, Integer.MAX_VALUE, contractId, null, null);
			List<QuoteReplacement> replacementDevices = contractService.getReplacements(0, Integer.MAX_VALUE, contractId, null, null);
			if(quoteDevices.size()>0){
				for(QuoteDevice quoteDevice : quoteDevices){
					sum += quoteDevice.getNumber() * quoteDevice.getUnitPrice();
				}
			}
			if(replacementDevices.size()>0){
				for(QuoteReplacement replacementDevice : replacementDevices){
					if(replacementDevice.getContractType().equals("备件合同")){
						sum += (replacementDevice.getPrice()==null?0:replacementDevice.getPrice());
					}else{
						sum += replacementDevice.getAmount() * (replacementDevice.getPrice()==null?0:replacementDevice.getPrice());
					}
				}
			}
			if(sum > totalSum){
				return 1;
			} else if(sum < totalSum){
				return 2;
			}else{
				return 0;
			}
		}
		
		/**
		 * 导出所有合同
		 * @param key
		 * @param request
		 * @return
		 * @throws UnsupportedEncodingException
		 */
		@RequestMapping(value = "/exportSelectsAll", method = RequestMethod.GET)
		public ResponseEntity<org.springframework.core.io.Resource> exportSelectsAll( HttpServletRequest request)
				throws UnsupportedEncodingException {	
			Map<String, Object> map = new HashMap<String, Object>();
			Map<String, Object> qMap = new HashMap<String, Object>();
			Map<String, Object> condition = new HashMap<String, Object>();
			Map<String, Object>numMap=new HashMap<String, Object>();
			//int start = Integer.parseInt(request.getParameter("start"));
			//int length = Integer.parseInt(request.getParameter("length"));
			Account a = this.getMyAccount();
			Module module = this.getPageModule("contractInfo");
			String dataFilter = module.getDataFilter();
			User user = a.getUser();
			//this.getQueryParams(qMap,numMap);
			condition.put("dataFilter", dataFilter);
			condition.put("qMap", qMap);
			condition.put("numMap", numMap);
			List<ContractInfo> contracts = contractService.getQueryContractsHql(0, 1000000, condition, user, "createTime",
					"desc");
			return this.excelService.toExcel(contracts, "合同信息.xlsx");
		}
}
